package org.example.handler;

import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.MessageContext.Scope;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * Handler para extraer los detalles del addressing
 **/

public class ServerHandler implements SOAPHandler<SOAPMessageContext> {
	private static final String REPLY_TO_ADDRESS = "http://localhost:8080/WS_CallBack/CallBackWS";
	
	@Override
	public boolean handleMessage(SOAPMessageContext context) {
		Boolean isOutbound = (Boolean) context.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY);
		try {
			
			SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
			SOAPHeader header = envelope.getHeader();
		
			if (!isOutbound) { //mensaje entrante
				/* Almacena en el contexto de la aplicación el MessageId que identifica el mensaje SOAP entrante
			y el ReplyTo, que indica a quien se debe responder */
				context.put("MessageID", getMessageID(header));
				context.setScope("MessageID", Scope.APPLICATION);
				
			//	context.put("ReplyTo", getReplyTo(header));
				context.put("ReplyTo", REPLY_TO_ADDRESS);
				
				context.setScope("ReplyTo", Scope.APPLICATION);
			}
				
		} catch (Exception ex) {
			throw new RuntimeException(ex);
		}

		return true;
	}
	
	protected String getReplyTo(SOAPHeader header) {
		NodeList nodeListReplyTo = header.getElementsByTagName("ReplyTo");
		NodeList nodeListAddress = nodeListReplyTo.item(0).getChildNodes();
		for (int i = 0; i < nodeListAddress.getLength(); i++) {
			Node node = nodeListAddress.item(i);
			if ("Address".equals(node.getLocalName())) {
				return node.getTextContent();
			}
		}
		return null;
	}
	
	protected String getMessageID(SOAPHeader header) {
		NodeList nodeListMessageId = header.getElementsByTagName("MessageID");
		return nodeListMessageId.item(0).getTextContent();
	}

	@Override
	public void close(MessageContext context) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean handleFault(SOAPMessageContext context) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public Set<QName> getHeaders() {
		// TODO Auto-generated method stub
		return null;
	}

}
